<html>
<body onload='startTest()'>

<script src="../../resources/js-test.js"></script>

<script>

// 'visibilitychange' event should bubble as defined in http://www.w3.org/TR/page-visibility/#sec-processing-model
// See: http://crbug.com/501821
description("This test checks that 'visibilitychange' event bubbles.");

var jsTestIsAsync = true;

function makePageVisible() {
    if (window.testRunner)
        testRunner.setMainWindowHidden(false);
}

function makePageHidden() {
    if (window.testRunner)
        testRunner.setMainWindowHidden(true);
}

function checkIsPageVisible() {
    shouldBeEqualToString("document.visibilityState", "visible");
    shouldBeFalse("document.hidden");
}

function checkIsPageHidden() {
    shouldBeEqualToString("document.visibilityState", "hidden");
    shouldBeTrue("document.hidden");
}

// We will try to change the visibility states as:
//  0 - visible. (Initial - i.e. on load).
//  1 - hidden (should fire event and bubbles).
//  2 - visible (should fire event and bubbles).
var numVisibilityChanges = 0;

function startTest() {
    // Document listener will be fired first
    document.addEventListener(
        "visibilitychange", onVisibilityChangeDocument, false);
    window.addEventListener(
        "visibilitychange", onVisibilityChangeWindow, false);
    checkIsPageVisible();
    numVisibilityChanges++;
    makePageHidden();
}

function onVisibilityChangeDocument(event) {
    shouldBeTrue("event.bubbles");
}

function onVisibilityChangeWindow(event) {
    shouldBeTrue("event.bubbles");
    if (numVisibilityChanges == 1) {
        numVisibilityChanges++;
        checkIsPageHidden();
        makePageVisible();
    } else if (numVisibilityChanges == 2) {
        finishJSTest();
    } else {
        testFailed("Invalid number of visibility transitions");
        finishJSTest();
    }
}

</script>


</body>
</html>
